<!-- 友链管理页面 - 提供友链的增删改查功能，支持搜索和筛选 -->
<template>
  <div class="friend-list">
    <!-- 示例数据提示 -->
    <el-alert v-if="isUsingSampleData" title="当前显示的是示例数据" description="由于后端API暂时不可用，正在显示示例数据。实际数据将在后端服务可用时自动加载。"
              type="info" :closable="false" show-icon class="sample-data-notice" />

    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">友链管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon>
          <Plus />
        </el-icon>
        添加友链
      </el-button>
    </div>

    <!-- 统计信息卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon friends-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ friends.length }}</div>
              <div class="stat-label">友链总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon active-icon">
              <el-icon>
                <Check />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ activeFriendsCount }}</div>
              <div class="stat-label">活跃友链</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon pending-icon">
              <el-icon>
                <Loading />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ pendingApplicationsCount }}</div>
              <div class="stat-label">待审核申请</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total-icon">
              <el-icon>
                <View />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ applications.length }}</div>
              <div class="stat-label">申请总数</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" class="friend-tabs" @tab-change="handleTabChange">
      <el-tab-pane label="友链列表" name="friends">
        <!-- 友链列表内容 -->
        <div class="tab-content">
          <!-- 搜索和筛选区域 -->
          <div class="filter-section">
            <!-- 搜索输入框 -->
            <el-input v-model="searchKeyword" placeholder="搜索友链名称..." class="search-input" clearable
                      @input="handleSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>

            <!-- 分类筛选 -->
            <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="handleFilter">
              <el-option label="技术博客" value="tech" />
              <el-option label="个人博客" value="personal" />
              <el-option label="工具网站" value="tools" />
              <el-option label="其他" value="other" />
              <!-- 动态添加的自定义分类 -->
              <el-option v-for="customCategory in customCategories" :key="customCategory.value"
                         :label="customCategory.label" :value="customCategory.value" />
            </el-select>

            <!-- 状态筛选 -->
            <el-select v-model="selectedStatus" placeholder="选择状态" clearable @change="handleFilter">
              <el-option label="活跃" value="active" />
              <el-option label="非活跃" value="inactive" />
            </el-select>
          </div>

          <!-- 友链列表网格布局 -->
          <div class="friend-grid" v-loading="isLoading">
            <!-- 友链卡片，循环渲染所有友链 -->
            <div v-for="friend in filteredFriends" :key="friend.id" class="friend-card">
              <!-- 友链卡片头部 -->
              <div class="friend-header">
                <!-- 友链Logo -->
                <img :src="friend.logo || '/src/assets/contact-avatar.svg'" :alt="friend.name" class="friend-logo" />
                <!-- 友链基本信息 -->
                <div class="friend-info">
                  <h3 class="friend-name">{{ friend.name }}</h3>
                  <p class="friend-url">{{ friend.url }}</p>
                </div>
                <!-- 友链状态标签 -->
                <el-tag :type="friend.status === 'active' ? 'success' : 'info'" size="small">
                  {{ friend.status === 'active' ? '活跃' : '非活跃' }}
                </el-tag>
              </div>

              <!-- 友链描述 -->
              <p class="friend-description">{{ friend.description }}</p>

              <!-- 友链元信息 -->
              <div class="friend-meta">
                <el-tag size="small" type="warning">{{ getCategoryName(friend.category) }}</el-tag>
                <span class="friend-date">{{ formatDate(friend.createTime) }}</span>
              </div>

              <!-- 友链操作按钮 -->
              <div class="friend-actions">
                <el-button size="small" @click="editFriend(friend)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="deleteFriend(friend.id)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="友链申请" name="applications">
        <!-- 友链申请内容 -->
        <div class="tab-content">
          <!-- 申请筛选区域 -->
          <div class="filter-section">
            <!-- 搜索输入框 -->
            <el-input v-model="applicationSearchKeyword" placeholder="搜索申请名称..." class="search-input" clearable
                      @input="handleApplicationSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>

            <!-- 申请状态筛选 -->
            <el-select v-model="selectedApplicationStatus" placeholder="选择状态" clearable
                       @change="handleApplicationFilter">
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </div>

          <!-- 友链申请列表 -->
          <div class="application-list" v-loading="isApplicationLoading">
            <div v-for="application in filteredApplications" :key="application.id" class="application-card">
              <!-- 申请卡片头部 -->
              <div class="application-header">
                <!-- 申请Logo -->
                <img :src="application.logo || '/src/assets/contact-avatar.svg'" :alt="application.name"
                     class="application-logo" />
                <!-- 申请基本信息 -->
                <div class="application-info">
                  <h3 class="application-name">{{ application.name }}</h3>
                  <p class="application-url">{{ application.url }}</p>
                </div>
                <!-- 申请状态标签 -->
                <el-tag :type="getApplicationStatusType(application.status)" size="small">
                  {{ getApplicationStatusText(application.status) }}
                </el-tag>
              </div>

              <!-- 申请描述 -->
              <p class="application-description">{{ application.description }}</p>

              <!-- 申请元信息 -->
              <div class="application-meta">
                <el-tag size="small" type="warning">{{ getCategoryName(application.category) }}</el-tag>
                <span class="application-date">{{ formatDate(application.createTime) }}</span>

              </div>

              <!-- 申请操作按钮 -->
              <div class="application-actions" v-if="application.status === 'pending'">
                <el-button size="small" type="success" @click="approveApplication(application)">
                  <el-icon>
                    <Check />
                  </el-icon>
                  通过
                </el-button>
                <el-button size="small" type="danger" @click="rejectApplication(application)">
                  <el-icon>
                    <Close />
                  </el-icon>
                  拒绝
                </el-button>
                <el-button size="small" @click="viewApplicationDetail(application)">
                  <el-icon>
                    <View />
                  </el-icon>
                  查看详情
                </el-button>
              </div>

              <!-- 已处理申请的显示 -->
              <div class="application-processed" v-else>
                <el-button size="small" @click="viewApplicationDetail(application)">
                  <el-icon>
                    <View />
                  </el-icon>
                  查看详情
                </el-button>
                <span class="process-time">处理时间: {{ formatDate(application.processTime || application.updateTime)
                  }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 友链申请详情对话框 -->
    <el-dialog v-model="showApplicationDetailDialog" title="友链申请详情" width="700px" :close-on-click-modal="false">
      <div v-if="selectedApplication" class="application-detail">
        <!-- 申请基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">
            <el-icon>
              <Link />
            </el-icon>
            基本信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>网站名称：</label>
              <span class="site-name">{{ selectedApplication.name }}</span>
            </div>
            <div class="info-item">
              <label>网站地址：</label>
              <a :href="selectedApplication.url" target="_blank" class="url-link">{{ selectedApplication.url }}</a>
            </div>
            <div class="info-item">
              <label>网站分类：</label>
              <el-tag size="small" type="warning" class="category-tag">{{ getCategoryName(selectedApplication.category)
                }}</el-tag>
            </div>
          </div>
        </div>

        <!-- 网站描述 -->
        <div class="detail-section">
          <h3 class="section-title">
            <el-icon>
              <Document />
            </el-icon>
            网站描述
          </h3>
          <div class="description-content">
            {{ selectedApplication.description }}
          </div>
        </div>

        <!-- 申请信息 -->
        <div class="detail-section">
          <h3 class="section-title">
            <el-icon>
              <Clock />
            </el-icon>
            申请信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>申请时间：</label>
              <span class="time-value">{{ formatDate(selectedApplication.createTime) }}</span>
            </div>
            <div class="info-item">
              <label>申请状态：</label>
              <el-tag :type="getApplicationStatusType(selectedApplication.status)" size="small" class="status-tag">
                {{ getApplicationStatusText(selectedApplication.status) }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 申请留言 -->
        <div class="detail-section" v-if="selectedApplication.applicantMessage">
          <h3 class="section-title">
            <el-icon>
              <ChatDotRound />
            </el-icon>
            申请留言
          </h3>
          <div class="message-content">
            {{ selectedApplication.applicantMessage }}
          </div>
        </div>

        <!-- 处理信息 -->
        <div class="detail-section" v-if="selectedApplication.status !== 'pending'">
          <h3 class="section-title">
            <el-icon>
              <Check />
            </el-icon>
            处理信息
          </h3>
          <div class="info-grid">
            <div class="info-item">
              <label>处理时间：</label>
              <span class="time-value">{{ formatDate(selectedApplication.processTime || selectedApplication.updateTime
                  ||
                  '') }}</span>
            </div>
            <div class="info-item">
              <label>处理备注：</label>
              <span class="process-note">{{ selectedApplication.processNote || '无' }}</span>
            </div>
          </div>
        </div>

        <!-- 网站Logo预览 -->
        <div class="detail-section" v-if="selectedApplication.logo">
          <h3 class="section-title">
            <el-icon>
              <Picture />
            </el-icon>
            网站Logo
          </h3>
          <div class="logo-preview">
            <img :src="selectedApplication.logo" :alt="selectedApplication.name" class="preview-logo" />
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showApplicationDetailDialog = false">关闭</el-button>
          <el-button v-if="selectedApplication?.status === 'pending'" type="success"
                     @click="approveApplicationFromDetail">
            <el-icon>
              <Check />
            </el-icon>
            通过申请
          </el-button>
          <el-button v-if="selectedApplication?.status === 'pending'" type="danger"
                     @click="rejectApplicationFromDetail">
            <el-icon>
              <Close />
            </el-icon>
            拒绝申请
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑友链对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingFriend ? '编辑友链' : '添加友链'" width="600px"
               :close-on-click-modal="false">
      <el-form :model="friendForm" :rules="friendRules" ref="friendFormRef" label-width="100px">
        <!-- 友链名称输入框 -->
        <el-form-item label="友链名称" prop="name">
          <input v-model="friendForm.name" placeholder="请输入友链名称"
                 style="width: 100%; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;" />
        </el-form-item>

        <!-- 友链URL输入框 -->
        <el-form-item label="友链链接" prop="url">
          <input v-model="friendForm.url" placeholder="请输入友链URL，例如：https://example.com"
                 style="width: 100%; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;" />
        </el-form-item>

        <!-- Logo URL输入框 -->
        <el-form-item label="Logo地址" prop="logo">
          <input v-model="friendForm.logo" placeholder="请输入Logo图片URL，例如：https://example.com/logo.png"
                 style="width: 100%; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px;" />
        </el-form-item>

        <!-- 友链描述输入框 -->
        <el-form-item label="友链描述" prop="description">
          <textarea v-model="friendForm.description" placeholder="请输入友链描述"
                    style="width: 100%; padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 4px; font-size: 14px; min-height: 80px; resize: vertical;" />
        </el-form-item>

        <!-- 分类选择 -->
        <el-form-item label="友链分类" prop="category">
          <div class="category-container">
            <!-- 分类选择下拉框 -->
            <el-select v-model="friendForm.category" placeholder="请选择分类" style="width: 100%; margin-bottom: 12px;"
                       @change="handleCategoryChange">
              <el-option label="技术博客" value="tech" />
              <el-option label="个人博客" value="personal" />
              <el-option label="工具网站" value="tools" />
              <el-option label="其他" value="other" />
              <!-- 动态添加的自定义分类 -->
              <el-option v-for="customCategory in customCategories" :key="customCategory.value"
                         :label="customCategory.label" :value="customCategory.value" />
            </el-select>

            <!-- 或者输入自定义分类 -->
            <div class="custom-category-section">
              <div class="section-title">或者添加自定义分类：</div>
              <div class="custom-category-input">
                <el-input v-model="newCategoryName" placeholder="输入新分类名称" size="small"
                          style="width: 200px; margin-right: 8px;" />
                <el-button type="primary" size="small" @click="addCustomCategory" :disabled="!newCategoryName.trim()">
                  添加分类
                </el-button>
              </div>

              <!-- 已添加的自定义分类列表 -->
              <div class="custom-categories-list" v-if="customCategories.length > 0">
                <div class="list-title">自定义分类：</div>
                <div class="categories-tags">
                  <el-tag v-for="category in customCategories" :key="category.value" closable size="small"
                          type="success" @close="removeCustomCategory(category.value)" class="category-tag">
                    {{ category.label }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 状态选择 -->
        <el-form-item label="友链状态" prop="status">
          <div style="display: flex; gap: 16px;">
            <label style="display: flex; align-items: center; gap: 4px;">
              <input type="radio" v-model="friendForm.status" value="active" />
              活跃
            </label>
            <label style="display: flex; align-items: center; gap: 4px;">
              <input type="radio" v-model="friendForm.status" value="inactive" />
              非活跃
            </label>
          </div>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveFriend" :loading="isSaving">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 导入Vue 3 Composition API核心功能
import { ref, reactive, computed, onMounted } from 'vue'
// 导入Element Plus组件和消息提示
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入Element Plus图标组件
import { Plus, Search, Edit, Delete, Loading, Check, Close, View, Clock, Link, Document, ChatDotRound, Picture } from '@element-plus/icons-vue'
// 导入API工具函数和常量
import { get, post, put, del, API_PATHS } from '@/utils/api'

// 状态管理
const isUsingSampleData = ref(false)
const isLoading = ref(false)
const isSaving = ref(false)
const isApplicationLoading = ref(false) // 新增：友链申请加载状态

// 标签页管理
const activeTab = ref('friends') // 当前激活的标签页

// 友链申请相关
const applicationSearchKeyword = ref('') // 申请搜索关键词
const selectedApplicationStatus = ref('') // 选中的申请状态
const applications = ref<FriendApplication[]>([]) // 友链申请数据数组
const showApplicationDetailDialog = ref(false) // 申请详情对话框显示状态
const selectedApplication = ref<FriendApplication | null>(null) // 当前选中的申请

// 类型定义
interface Friend {
  id: number
  name: string
  url: string
  description: string
  logo?: string
  category: string
  status: 'active' | 'inactive'
  createTime: string
  updateTime?: string
  sort?: number
}

interface FriendRequest {
  name: string
  url: string
  description: string
  logo?: string
  category: string
  status: 'active' | 'inactive'
  sort?: number
}

interface FriendResponse {
  friends: Friend[]
  total: number
  categories: string[]
}

// 友链申请接口
interface FriendApplication {
  id: number
  name: string
  url: string
  description: string
  logo?: string
  category: string
  status: 'pending' | 'approved' | 'rejected'
  createTime: string
  updateTime: string
  processTime?: string
  processNote?: string
  applicantMessage?: string
}

// 友链申请响应接口
interface FriendApplicationResponse {
  success: boolean
  data: FriendApplication[]
  message?: string
  error?: string
}

// 友链申请审核请求接口
interface FriendApplicationReviewRequest {
  status: 'approved' | 'rejected'
  processNote?: string
}

// 友链申请审核响应接口
interface FriendApplicationReviewResponse {
  success: boolean
  data: FriendApplication
  message?: string
  error?: string
}

// 友链申请统计接口
interface FriendApplicationStatsResponse {
  success: boolean
  data: {
    total: number
    pending: number
    approved: number
    rejected: number
  }
  message?: string
  error?: string
}

interface FriendStats {
  total: number
  active: number
  inactive: number
  categories: { [key: string]: number }
}

// 示例数据
const sampleFriends: Friend[] = [
  {
    id: 1,
    name: '张三的博客',
    url: 'https://zhangsan.com',
    description: '一个专注于前端技术的个人博客，分享Vue、React、TypeScript等技术文章',
    logo: '/src/assets/default-avatar.svg',
    category: 'tech',
    status: 'active',
    createTime: '2024-01-15T10:30:00Z',
    updateTime: '2024-01-20T14:20:00Z',
    sort: 1
  },
  {
    id: 2,
    name: '李四的网站',
    url: 'https://lisi.net',
    description: '分享生活感悟和读书笔记，记录成长历程',
    logo: '/src/assets/default-avatar.svg',
    category: 'personal',
    status: 'active',
    createTime: '2024-01-10T09:15:00Z',
    updateTime: '2024-01-18T16:45:00Z',
    sort: 2
  },
  {
    id: 3,
    name: '工具集合',
    url: 'https://tools.example.com',
    description: '各种实用的在线工具，提高工作效率',
    logo: '/src/assets/default-avatar.svg',
    category: 'tools',
    status: 'inactive',
    createTime: '2024-01-05T11:20:00Z',
    updateTime: '2024-01-12T13:30:00Z',
    sort: 3
  },
  {
    id: 4,
    name: '设计资源库',
    url: 'https://design.example.com',
    description: '优质的设计资源和灵感分享平台',
    logo: '/src/assets/default-avatar.svg',
    category: 'other',
    status: 'active',
    createTime: '2024-01-08T15:40:00Z',
    updateTime: '2024-01-15T10:25:00Z',
    sort: 4
  }
]

// 友链申请示例数据
const sampleApplications: FriendApplication[] = [
  {
    id: 1,
    name: '前端开发者的日常',
    url: 'https://frontend-daily.com',
    description: '分享前端开发经验和技巧，包含Vue、React、Angular等框架的实战案例',
    logo: '/src/assets/contact-avatar.svg',
    category: 'tech',
    status: 'pending',
    applicantMessage: '希望能与您的博客建立友链，共同分享技术经验',
    createTime: '2024-01-25T14:30:00Z',
    updateTime: '2024-01-25T14:30:00Z'
  },
  {
    id: 2,
    name: '生活随笔集',
    url: 'https://life-notes.com',
    description: '记录生活中的点点滴滴，分享人生感悟和思考',
    logo: '/src/assets/contact-avatar.svg',
    category: 'personal',
    status: 'approved',
    applicantMessage: '很喜欢您的博客风格，希望能建立友链',
    createTime: '2024-01-20T09:15:00Z',
    updateTime: '2024-01-20T09:15:00Z',
    processTime: '2024-01-22T16:45:00Z',
    processNote: '内容质量不错，符合友链要求'
  },
  {
    id: 3,
    name: '在线工具大全',
    url: 'https://online-tools.com',
    description: '提供各种实用的在线工具，包括图片处理、文本转换、计算器等',
    logo: '/src/assets/contact-avatar.svg',
    category: 'tools',
    status: 'rejected',
    applicantMessage: '我们的工具网站希望能与您建立友链',
    createTime: '2024-01-18T11:20:00Z',
    updateTime: '2024-01-18T11:20:00Z',
    processTime: '2024-01-19T14:30:00Z',
    processNote: '网站内容与博客主题不够匹配'
  },
  {
    id: 4,
    name: 'AI技术探索',
    url: 'https://ai-explore.com',
    description: '专注于人工智能技术的研究和应用，分享最新的AI发展动态和实用技巧',
    logo: '/src/assets/contact-avatar.svg',
    category: 'tech',
    status: 'pending',
    applicantMessage: '我们的AI技术博客希望能与您建立友链，共同探讨技术发展',
    createTime: '2024-01-26T10:15:00Z',
    updateTime: '2024-01-26T10:15:00Z'
  },
  {
    id: 5,
    name: '摄影艺术分享',
    url: 'https://photo-art.com',
    description: '分享摄影技巧和艺术作品，记录生活中的美好瞬间',
    logo: '/src/assets/contact-avatar.svg',
    category: 'other',
    status: 'pending',
    applicantMessage: '希望能与您的博客建立友链，分享艺术之美',
    createTime: '2024-01-27T16:30:00Z',
    updateTime: '2024-01-27T16:30:00Z'
  }
]

const sampleCategories = ['技术博客', '个人博客', '工具网站', '其他']

// 使用示例数据的函数
const useSampleData = () => {
  isUsingSampleData.value = true
  friends.value = sampleFriends
}

// 响应式数据定义
const searchKeyword = ref('') // 搜索关键词
const selectedCategory = ref('') // 选中的分类
const selectedStatus = ref('') // 选中的状态
const showAddDialog = ref(false) // 对话框显示状态
const editingFriend = ref<Friend | null>(null) // 当前编辑的友链对象
const friendFormRef = ref() // 表单引用

// 自定义分类相关
const customCategories = ref<Array<{ label: string, value: string }>>([]) // 自定义分类列表
const newCategoryName = ref('') // 新分类名称输入

// 友链数据数组
const friends = ref<Friend[]>([])

// 友链表单数据对象
const friendForm = reactive({
  name: '', // 友链名称
  url: '', // 友链URL
  description: '', // 友链描述
  logo: '', // Logo URL
  category: '', // 分类
  status: 'active' // 状态
})

// 表单验证规则配置
const friendRules = {
  name: [{ required: true, message: '请输入友链名称', trigger: 'blur' }],
  url: [
    { required: true, message: '请输入友链URL', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL', trigger: 'blur' }
  ],
  description: [{ required: true, message: '请输入友链描述', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 计算属性：根据搜索和筛选条件过滤友链列表
const filteredFriends = computed(() => {
  return friends.value.filter(friend => {
    // 关键词匹配：检查名称和描述是否包含搜索关键词
    const matchKeyword = !searchKeyword.value ||
        friend.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        friend.description.toLowerCase().includes(searchKeyword.value.toLowerCase())

    // 分类匹配
    const matchCategory = !selectedCategory.value || friend.category === selectedCategory.value
    // 状态匹配
    const matchStatus = !selectedStatus.value || friend.status === selectedStatus.value

    return matchKeyword && matchCategory && matchStatus
  })
})

// 计算属性：根据搜索和筛选条件过滤友链申请列表
const filteredApplications = computed(() => {
  return applications.value.filter(application => {
    // 关键词匹配：检查名称和描述是否包含搜索关键词
    const matchKeyword = !applicationSearchKeyword.value ||
        application.name.toLowerCase().includes(applicationSearchKeyword.value.toLowerCase()) ||
        application.description.toLowerCase().includes(applicationSearchKeyword.value.toLowerCase())

    // 状态匹配
    const matchStatus = !selectedApplicationStatus.value || application.status === selectedApplicationStatus.value

    return matchKeyword && matchStatus
  })
})

// 计算属性：活跃友链数量
const activeFriendsCount = computed(() => {
  return friends.value.filter(friend => friend.status === 'active').length
})

// 计算属性：待审核申请数量
const pendingApplicationsCount = computed(() => {
  return applications.value.filter(application => application.status === 'pending').length
})

// 方法定义

/**
 * 处理搜索输入
 * 搜索逻辑已在计算属性中处理
 */
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

/**
 * 处理筛选条件变化
 * 筛选逻辑已在计算属性中处理
 */
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

/**
 * 处理标签页切换
 * @param tabName - 切换到的标签页名称
 */
const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  if (tabName === 'applications' && applications.value.length === 0) {
    // 切换到友链申请标签页时，如果没有数据则加载示例数据
    loadSampleApplications()
  }
}

/**
 * 处理友链申请搜索
 * 搜索逻辑已在计算属性中处理
 */
const handleApplicationSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

/**
 * 处理友链申请筛选
 * 筛选逻辑已在计算属性中处理
 */
const handleApplicationFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

/**
 * 获取申请状态对应的标签类型
 * @param status - 申请状态
 * @returns 标签类型
 */
const getApplicationStatusType = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

/**
 * 获取申请状态对应的中文文本
 * @param status - 申请状态
 * @returns 中文状态文本
 */
const getApplicationStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

/**
 * 查看友链申请详情
 * @param application - 要查看的申请
 */
const viewApplicationDetail = (application: FriendApplication) => {
  selectedApplication.value = application
  showApplicationDetailDialog.value = true
}

/**
 * 通过友链申请 (从详情对话框)
 */
const approveApplicationFromDetail = async () => {
  if (selectedApplication.value) {
    await approveApplication(selectedApplication.value)
    showApplicationDetailDialog.value = false
  }
}

/**
 * 拒绝友链申请 (从详情对话框)
 */
const rejectApplicationFromDetail = async () => {
  if (selectedApplication.value) {
    await rejectApplication(selectedApplication.value)
    showApplicationDetailDialog.value = false
  }
}

/**
 * 加载友链申请示例数据
 */
const loadSampleApplications = () => {
  isApplicationLoading.value = true
  setTimeout(() => {
    applications.value = [...sampleApplications]
    isApplicationLoading.value = false
  }, 500)
}

/**
 * 格式化日期显示
 * @param date - 日期字符串
 * @returns 格式化后的本地日期字符串
 */
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

/**
 * 获取分类的中文名称
 * @param category - 分类代码
 * @returns 分类的中文名称
 */
const getCategoryName = (category: string) => {
  const categoryMap: { [key: string]: string } = {
    'tech': '技术博客',
    'personal': '个人博客',
    'tools': '工具网站',
    'other': '其他'
  }

  // 检查是否是自定义分类
  if (category.startsWith('custom_')) {
    const customCategory = customCategories.value.find(cat => cat.value === category)
    if (customCategory) {
      return customCategory.label
    }
  }

  return categoryMap[category] || category
}

/**
 * 处理分类选择变化
 * @param value - 选中的分类值
 */
const handleCategoryChange = (value: string) => {
  friendForm.category = value
}

/**
 * 添加自定义分类
 * 将新分类添加到自定义分类列表中
 */
const addCustomCategory = () => {
  const categoryName = newCategoryName.value.trim()
  if (categoryName) {
    // 检查是否已存在相同名称的分类
    const exists = customCategories.value.some(cat => cat.label === categoryName)
    if (exists) {
      ElMessage.warning('该分类名称已存在')
      return
    }

    // 生成唯一的分类值
    const categoryValue = `custom_${Date.now()}`

    // 添加到自定义分类列表
    customCategories.value.push({
      label: categoryName,
      value: categoryValue
    })

    // 自动选中新添加的分类
    friendForm.category = categoryValue

    // 清空输入框
    newCategoryName.value = ''

    ElMessage.success('自定义分类添加成功')
  }
}

/**
 * 删除自定义分类
 * @param categoryValue - 要删除的分类值
 */
const removeCustomCategory = (categoryValue: string) => {
  const index = customCategories.value.findIndex(cat => cat.value === categoryValue)
  if (index > -1) {
    // 如果当前选中的是被删除的分类，清空选择
    if (friendForm.category === categoryValue) {
      friendForm.category = ''
    }

    customCategories.value.splice(index, 1)
    ElMessage.success('自定义分类删除成功')
  }
}

/**
 * 编辑友链
 * 将友链数据填充到表单中并打开编辑对话框
 * @param friend - 要编辑的友链对象
 */
const editFriend = (friend: Friend) => {
  editingFriend.value = friend
  Object.assign(friendForm, friend)
  showAddDialog.value = true
}

/**
 * 取消编辑
 * 关闭对话框并重置表单
 */
const cancelEdit = () => {
  showAddDialog.value = false
  resetForm()
}

/**
 * 获取友链列表
 * 从API获取友链数据
 */
const fetchFriends = async () => {
  isLoading.value = true
  try {
    const response = await get(API_PATHS.ADMIN_FRIENDS.LIST, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success && response.data) {
      const data = response.data as FriendResponse
      friends.value = data.friends
      isUsingSampleData.value = false
    } else {
      // 如果API返回成功但没有数据，也使用示例数据
      useSampleData()
    }
  } catch (error) {
    ElMessage.error('获取友链列表失败，正在显示示例数据')
    console.error('Error fetching friends:', error)
    // 使用示例数据作为降级
    useSampleData()
  } finally {
    isLoading.value = false
  }
}

/**
 * 创建友链
 * @param friendData - 友链数据
 */
const createFriendAPI = async (friendData: FriendRequest) => {
  try {
    const response = await post(API_PATHS.ADMIN_FRIENDS.CREATE, friendData, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      ElMessage.success('创建友链成功')
      await fetchFriends() // 重新获取列表
      return true
    }
    return false
  } catch (error) {
    ElMessage.error('创建友链失败')
    console.error('Error creating friend:', error)
    return false
  }
}

/**
 * 更新友链
 * @param id - 友链ID
 * @param friendData - 友链数据
 */
const updateFriendAPI = async (id: number, friendData: FriendRequest) => {
  try {
    const response = await put(API_PATHS.ADMIN_FRIENDS.UPDATE(id.toString()), friendData, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      ElMessage.success('更新友链成功')
      await fetchFriends() // 重新获取列表
      return true
    }
    return false
  } catch (error) {
    ElMessage.error('更新友链失败')
    console.error('Error updating friend:', error)
    return false
  }
}

/**
 * 删除友链
 * 删除前会显示确认对话框
 * @param id - 要删除的友链ID
 */
const deleteFriend = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个友链吗？', '确认删除', {
      type: 'warning'
    })

    const response = await del(API_PATHS.ADMIN_FRIENDS.DELETE(id.toString()), {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success) {
      ElMessage.success('删除成功')
      await fetchFriends() // 重新获取列表
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除友链失败')
      console.error('Error deleting friend:', error)
    }
  }
}

/**
 * 保存友链
 * 根据是否为编辑模式执行添加或更新操作
 */
const saveFriend = async () => {
  try {
    // 验证表单数据
    await friendFormRef.value.validate()

    isSaving.value = true

    const friendData: FriendRequest = {
      name: friendForm.name,
      url: friendForm.url,
      description: friendForm.description,
      logo: friendForm.logo || undefined,
      category: friendForm.category,
      status: friendForm.status as 'active' | 'inactive'
    }

    let success = false
    if (editingFriend.value) {
      // 编辑模式：更新现有友链
      success = await updateFriendAPI(editingFriend.value.id, friendData)
    } else {
      // 添加模式：创建新友链
      success = await createFriendAPI(friendData)
    }

    if (success) {
      showAddDialog.value = false
      resetForm()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    isSaving.value = false
  }
}

/**
 * 重置表单
 * 清空表单数据并重置编辑状态
 */
const resetForm = () => {
  editingFriend.value = null
  Object.assign(friendForm, {
    name: '',
    url: '',
    description: '',
    logo: '',
    category: '',
    status: 'active'
  })
  // 清空自定义分类相关数据
  newCategoryName.value = ''
  friendFormRef.value?.resetFields()
}

/**
 * 获取友链申请列表
 * 从API获取友链申请数据，如果失败则使用示例数据
 */
const fetchApplications = async () => {
  isApplicationLoading.value = true
  try {
    const response = await get<FriendApplicationResponse>(API_PATHS.ADMIN_FRIENDS.APPLICATIONS, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success && response.data) {
      applications.value = response.data as unknown as FriendApplication[]
      isUsingSampleData.value = false
    } else {
      // 如果API返回成功但没有数据，也使用示例数据
      loadSampleApplications()
    }
  } catch (error) {
    ElMessage.error('获取友链申请列表失败，正在显示示例数据')
    console.error('Error fetching applications:', error)
    // 使用示例数据作为降级
    loadSampleApplications()
  } finally {
    isApplicationLoading.value = false
  }
}

/**
 * 获取友链申请统计信息
 * 从API获取申请统计数据，如果失败则使用本地计算
 */
const fetchApplicationStats = async () => {
  try {
    const response = await get<FriendApplicationStatsResponse>(API_PATHS.ADMIN_FRIENDS.APPLICATION_STATS, {
      timeout: 8000,
      retry: 2
    })

    if (response && response.success && response.data) {
      // 使用API返回的统计数据
      return response.data
    }
  } catch (error) {
    console.error('Error fetching application stats:', error)
  }

  // 如果API调用失败，返回本地计算的统计数据
  return {
    total: applications.value.length,
    pending: applications.value.filter(app => app.status === 'pending').length,
    approved: applications.value.filter(app => app.status === 'approved').length,
    rejected: applications.value.filter(app => app.status === 'rejected').length
  }
}

/**
 * 审核友链申请
 * 调用API审核友链申请，包括通过和拒绝操作
 * @param applicationId - 申请ID
 * @param reviewData - 审核数据（状态和处理备注）
 * @returns 审核是否成功
 */
const reviewApplicationAPI = async (applicationId: number, reviewData: FriendApplicationReviewRequest): Promise<boolean> => {
  try {
    const response = await post<FriendApplicationReviewResponse>(
        API_PATHS.ADMIN_FRIENDS.REVIEW_APPLICATION(applicationId.toString()),
        reviewData,
        {
          timeout: 8000,
          retry: 2
        }
    )

    if (response && response.success && response.data) {
      // 更新本地申请数据
      const index = applications.value.findIndex(app => app.id === applicationId)
      if (index !== -1) {
        applications.value[index] = response.data as unknown as FriendApplication
      }
      return true
    }
    return false
  } catch (error) {
    ElMessage.error('审核申请失败')
    console.error('Error reviewing application:', error)
    return false
  }
}

/**
 * 通过友链申请
 * 调用API通过友链申请，成功后可以选择添加到友链列表
 * @param application - 要通过的申请
 */
const approveApplication = async (application: FriendApplication) => {
  try {
    await ElMessageBox.confirm('确定要通过这个友链申请吗？', '确认通过', {
      type: 'warning'
    })

    // 调用API审核申请
    const success = await reviewApplicationAPI(application.id, {
      status: 'approved',
      processNote: '已通过审核'
    })

    if (success) {
      ElMessage.success('友链申请已通过')

      // 可以选择将通过的申请转换为友链
      // 这里可以调用添加友链的API
      const friendData: FriendRequest = {
        name: application.name,
        url: application.url,
        description: application.description,
        logo: application.logo,
        category: application.category,
        status: 'active'
      }

      // 添加到友链列表
      const friendSuccess = await createFriendAPI(friendData)
      if (friendSuccess) {
        ElMessage.success('友链已添加到友链列表')
        // 重新获取友链列表
        await fetchFriends()
      }
    } else {
      ElMessage.error('通过申请失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error('Error approving application:', error)
    }
  }
}

/**
 * 拒绝友链申请
 * 调用API拒绝友链申请，需要输入拒绝原因
 * @param application - 要拒绝的申请
 */
const rejectApplication = async (application: FriendApplication) => {
  try {
    const { value: rejectReason } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝申请', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入拒绝原因...'
    })

    if (rejectReason) {
      // 调用API审核申请
      const success = await reviewApplicationAPI(application.id, {
        status: 'rejected',
        processNote: rejectReason
      })

      if (success) {
        ElMessage.success('友链申请已拒绝')
      } else {
        ElMessage.error('拒绝申请失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
      console.error('Error rejecting application:', error)
    }
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  // 先尝试从API获取数据，如果失败则显示示例数据
  fetchFriends()
  fetchApplications()
})
</script>

<style scoped lang="scss">
// 导入友链管理页面样式
@use '../../assets/styles/admin/_friends';
</style>